package com.aimuceliang.aimuceliang.utils;

/**
 * Created by zhangjing on 2017/10/22.
 */
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.aimuceliang.aimuceliang.bean.LongChengBean;
import com.aimuceliang.aimuceliang.bean.TiChiBean;
import com.aimuceliang.aimuceliang.bean.WoChengBean;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import org.greenrobot.eventbus.EventBus;

/**
 * 会话界面
 *
 * @author chenlin
 * @version 1.0
 * @Project App_Bluetooth
 * @Package com.android.bluetooth
 * @Date 2013年3月2日
 * @Note TODO
 */
public class BluetoothChat {


    public static final int STATUS_CONNECT = 0x11;
    public static final int STATUS_CONNECTING = 0x08;
    public static final int STATUS_CONNECTERROR = 0x07;
    public static final int INPUT_MESSAGE_SUCESS = 0x12;
    public static final int OUTPUT_MESSAGE_SUCESS = 0x13;

    /* 一些常量，代表服务器的名称 */
    public static final String PROTOCOL_SCHEME_L2CAP = "btl2cap";
    public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";
    public static final String PROTOCOL_SCHEME_BT_OBEX = "btgoep";
    public static final String PROTOCOL_SCHEME_TCP_OBEX = "tcpobex";

    // 蓝牙服务端socket
    private BluetoothServerSocket mServerSocket;
    // 蓝牙客户端socket
    private BluetoothSocket mSocket;
    // 设备
    private BluetoothDevice mDevice;
    private BluetoothAdapter mBluetoothAdapter;

    // --线程类-----------------
    private ServerThread mServerThread;
    private ClientThread mClientThread;
    private ReadThread mReadThread;

    private Handler handler;

    private int uiDeviceType = 0;  // 0-未知 1-笼秤 2-窝秤 3-体尺

    public static BluetoothChat bluetoothChat;

    public static BluetoothChat getBluetoothChat(int iDeviceType){
        if(bluetoothChat == null){
            bluetoothChat = new BluetoothChat();
        }
        if(iDeviceType > 0) {
            bluetoothChat.uiDeviceType = iDeviceType;
        }
        return bluetoothChat;
    }


    public void setHandler(Handler handler){
        this.handler = null;
        this.handler = handler;
    }

    /**
     *连接设备
     * @param address
     */
    public void OpenThisDev(String address,Handler handler){
        this.handler = handler;
        mBluetoothAdapter  = BluetoothAdapter.getDefaultAdapter();
        if (!"".equals(address)) {
            mDevice = mBluetoothAdapter.getRemoteDevice(address);
            createBond(mDevice);
        } else {
            T.showLong("address is null");
        }
    }

    /**
     * 尝试配对和连接
     *
     * @param btDev
     */
    public void createBond(BluetoothDevice btDev) {
        if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
            //如果这个设备取消了配对，则尝试配对
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                btDev.createBond();
            }
        }
        mClientThread = new ClientThread();
        mClientThread.start();
        //mServerThread = new ServerThread();
        //mServerThread.start();
    }


    private void sendMessage(String msg) {
        // 发送信息
        byte[] data = msg.getBytes();
        sendMessageHandle(data);
    }


    // 客户端线程
    private class ClientThread extends Thread {
        public void run() {
            try {
                mSocket = mDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                Message msg = new Message();
                msg.obj = "请稍候，正在连接配对设备:";
                msg.what = STATUS_CONNECTING;
                handler.sendMessage(msg);
                mSocket.connect();

                msg = new Message();
                msg.obj = "已经连接上服务端！可以发送信息。";
                msg.what = STATUS_CONNECT;
                handler.sendMessage(msg);
                // 启动接受数据
                mReadThread = new ReadThread();
                mReadThread.start();
            } catch (IOException e) {
                Message msg = new Message();
                msg.obj = "连接服务端异常！请开启服务端再试";
                msg.what = STATUS_CONNECTERROR;
                handler.sendMessage(msg);
            }
        }
    }

    ;

    // 开启服务器
    private class ServerThread extends Thread {
        public void run() {
            try {
                // 创建一个蓝牙服务器 参数分别：服务器名称、UUID
                mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                Message msg = new Message();
                msg.obj = "请稍候，正在等待客户端的连接...";
                msg.what = STATUS_CONNECTING;
                handler.sendMessage(msg);

				/* 接受客户端的连接请求 */
                mSocket = mServerSocket.accept();

                msg = new Message();
                msg.obj = "客户端已经连接上！可以发送信息。";
                msg.what = STATUS_CONNECT;
                handler.sendMessage(msg);
                // 启动接受数据
                mReadThread = new ReadThread();
                mReadThread.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /* 停止服务器 */
    private void shutdownServer() {
        new Thread() {
            public void run() {
                if (mServerThread != null) {
                    mServerThread.interrupt();
                    mServerThread = null;
                }
                if (mReadThread != null) {
                    mReadThread.interrupt();
                    mReadThread = null;
                }
                try {
                    if (mSocket != null) {
                        mSocket.close();
                        mSocket = null;
                    }
                    if (mServerSocket != null) {
                        mServerSocket.close();
                        mServerSocket = null;
                    }
                } catch (IOException e) {
                    Log.e("server", "mserverSocket.close()", e);
                }
            }

            ;
        }.start();
    }

    /* ͣ停止客户端连接 */
    public void shutdownClient() {
        new Thread() {
            public void run() {
                if (mClientThread != null) {
                    mClientThread.interrupt();
                    mClientThread = null;
                }
                if (mReadThread != null) {
                    mReadThread.interrupt();
                    mReadThread = null;
                }
                if (mSocket != null) {
                    try {
                        mSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mSocket = null;
                }
            }

            ;
        }.start();
    }

    // 发送数据
    public void sendMessageHandle(byte[] msg) {
        if (mSocket == null) {
            T.showLong("建立连接失败");
            return;
        }
        try {
            OutputStream os = mSocket.getOutputStream();
            os.write(msg);
            String s = new String(msg);
            Message msg1 = new Message();
            msg1.obj = s;
            msg1.what = OUTPUT_MESSAGE_SUCESS;
            //handler.sendMessage(msg1);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 读取数据
    private class ReadThread extends Thread {
        public void run() {

            XLog.d("TTTT", "uiDeviceType::" + String.valueOf(uiDeviceType));

            if(1 == uiDeviceType) {
                // 笼秤
                readDataFromLongcheng();

            } else if(2 == uiDeviceType) {
                // 窝秤
                readDataFromWocheng();

            } else if(3 == uiDeviceType) {
                // 体尺
                readDataFromTichi();

            } else {
                // 未知秤
            }
        }
    }

    private void readDataFromTichi() {
        byte[] buffer   = new byte[1024];
        int bytes;
        byte[] data_get = null;
        InputStream is = null;
        try {
            is = mSocket.getInputStream();
            while (true) {

                byte[] buf_data = null;

                if ((bytes = is.read(buffer)) > 0) {
                    buf_data = new byte[bytes];
                    for (int i = 0; i < bytes; i++) {
                        buf_data[i] = buffer[i];
                    }
                }

                data_get = addBytes(data_get, buf_data);

                if(8 == data_get.length) {
                    // 如果结果和清除命令的返回值一样，则扔掉，不处理
                    byte[] data_clean = {0x01 ,0x06 ,0x10 , (byte) 0xD1,0x00 ,0x00 , (byte) 0xDD,0x33};

                    if( (data_get[0] == data_clean[0]) && (data_get[1] == data_clean[0]) && (data_get[2] == data_clean[0]) && (data_get[3] == data_clean[0]) &&
                         (data_get[4] == data_clean[0]) && (data_get[5] == data_clean[0]) && (data_get[6] == data_clean[0]) && (data_get[7] == data_clean[0]) ) {

                    } else {
                        data_get = null;
                    }

                } else if(45 == data_get.length) {
                    String sss = "";
                    for (int i = 0; i < data_get.length; i++) {
                        sss = sss + String.format("%02X ", data_get[i]);
                    }

                    tichiDataAnalysisUtil.ansyBlueData(data_get);
                    TiChiBean tiChiBean = new TiChiBean();
                    tiChiBean.strChest = tichiDataAnalysisUtil.strChest;
                    tiChiBean.strEarNum = tichiDataAnalysisUtil.strEarNum;
                    tiChiBean.strHeight = tichiDataAnalysisUtil.strHeight;
                    tiChiBean.strStaNum = tichiDataAnalysisUtil.strStaNum;
                    tiChiBean.strTime = tichiDataAnalysisUtil.strTime;
                    tiChiBean.strLength = tichiDataAnalysisUtil.strLength;
                    tiChiBean.strWeight = tichiDataAnalysisUtil.strWeight;
                    EventBus.getDefault().post(tiChiBean);

                    data_get = null;
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public static byte[] addBytes(byte[] data1, byte[] data2) {

        if((null == data1) && (null == data2)) {
            return null;
        }

        if((null == data1) && (null != data2)) {
            byte[] data3 = new byte[data2.length];
            System.arraycopy(data2, 0, data3, 0, data2.length);
            return data3;
        }

        if((null != data1) && (null == data2)) {
            byte[] data3 = new byte[data1.length];
            System.arraycopy(data1, 0, data3, 0, data1.length);
            return data3;
        }

        if((null != data1) && (null != data2)) {
            byte[] data3 = new byte[data1.length + data2.length];
            System.arraycopy(data1, 0, data3, 0, data1.length);
            System.arraycopy(data2, 0, data3, data1.length, data2.length);
            return data3;
        }

        return null;
    }

    private void readDataFromLongcheng() {
        byte[] buffer   = new byte[1024];
        int bytes;
        InputStream is = null;

        byte[] data_get = null;

        try {
            is = mSocket.getInputStream();
            while (true) {

                byte[] buf_data = null;

                if ((bytes = is.read(buffer)) > 0) {
                    buf_data = new byte[bytes];
                    for (int i = 0; i < bytes; i++) {
                        buf_data[i] = buffer[i];
                    }
                }

                data_get = addBytes(data_get, buf_data);

                if(data_get.length > 26) {
                    data_get = null;
                    continue;
                }

                if(26 == data_get.length) {
                    String sss = "";
                    for (int i = 0; i < data_get.length; i++) {
                        sss = sss + String.format("%02X ", data_get[i]);
                    }
                    XLog.d("TTTT", "==" + String.valueOf(data_get.length) + "==" + sss);

                    if(longchengDataAnalysisUtil.ansyBlueData(data_get)) {
                        LongChengBean LongChengBean = new LongChengBean();
                        LongChengBean.strEarNum = longchengDataAnalysisUtil.strEarNum;
                        LongChengBean.strWeight = longchengDataAnalysisUtil.strWeightTotal;
                        EventBus.getDefault().post(LongChengBean);
                    }

                    data_get = null;
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
            XLog.d("TTTT","e1::" + e1.getMessage());
        } finally {
            try {
                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
                XLog.d("TTTT","e2::" + e1.getMessage());
            }
        }
    }

    private void readDataFromWocheng() {
        byte[] buffer   = new byte[1024];
        int bytes;
        InputStream is = null;

        byte[] data_get = null;

        try {
            is = mSocket.getInputStream();
            while (true) {

                byte[] buf_data = null;

                if ((bytes = is.read(buffer)) > 0) {
                    buf_data = new byte[bytes];
                    for (int i = 0; i < bytes; i++) {
                        buf_data[i] = buffer[i];
                    }
                }

                data_get = addBytes(data_get, buf_data);

                if(data_get.length > 26) {
                    data_get = null;
                    continue;
                }

                if(26 == data_get.length) {
                    String sss = "";
                    for (int i = 0; i < data_get.length; i++) {
                        sss = sss + String.format("%02X ", data_get[i]);
                    }
                    XLog.d("TTTT", "==" + String.valueOf(data_get.length) + "==" + sss);

                    if(wochengDataAnalysisUtil.ansyBlueData(data_get)) {
                        WoChengBean woChengBean = new WoChengBean();
                        woChengBean.strEarNum = wochengDataAnalysisUtil.strEarNum;
                        woChengBean.strNumber = wochengDataAnalysisUtil.strNumber;
                        woChengBean.strWeightAll = wochengDataAnalysisUtil.strWeightTotal;
                        woChengBean.strWeightMin = wochengDataAnalysisUtil.strWeightMin;
                        woChengBean.strWeightMax = wochengDataAnalysisUtil.strWeightMax;
                        woChengBean.strWeightAvg = wochengDataAnalysisUtil.strWeightAvg;
                        EventBus.getDefault().post(woChengBean);
                    }

                    data_get = null;
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
            XLog.d("TTTT","e1::" + e1.getMessage());
        } finally {
            try {
                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
                XLog.d("TTTT","e2::" + e1.getMessage());
            }
        }
    }

}